
#include <node.h>
#include "calc.h"

using namespace std;
using namespace v8;

namespace lama{
    
    
    Persistent<Function> Calc::constructor;
    
    Calc::Calc()
    {
        
    }
    Calc::~Calc()
    {
        
    }
    
    void Calc::Init(Local<Object> exports)
    {
        Isolate* isolate=exports->GetIsolate();
        
        
        Local<FunctionTemplate> tpl=FunctionTemplate::New(isolate,New);
        tpl->SetClassName(String::NewFromUtf8(isolate,"Calc"));
        tpl->InstanceTemplate()->SetInternalFieldCount(1);
        
        /*
            是不是所有的方法都得写成静态的，然后通过这种方式添加
        */
        
        NODE_SET_PROTOTYPE_METHOD(tpl,"add",Add);
        
        constructor.Reset(isolate,tpl->GetFunction());
        exports->Set(String::NewFromUtf8(isolate,"Calc"),tpl->GetFunction());

    }
    
    void Calc::New(const FunctionCallbackInfo<Value>& args)
    {
        Isolate* isolate=args.GetIsolate();
        
        if(args.IsConstructCall())
        {
            Calc* calc=new Calc();
            calc->Wrap(args.This());
            args.GetReturnValue().Set(args.This());
        }
        else
        {
            const int argc=1;
            Local<Value> argv[argc]={args[0]};
            Local<Function> cons =Local<Function>::New(isolate,constructor);
            args.GetReturnValue().Set(cons->NewInstance(argc,argv));
        }
    }
    
    void Calc::Add(const FunctionCallbackInfo<Value>& args)
    {
        Isolate* isolate=args.GetIsolate();   
        
        double value=args[0]->NumberValue()+args[1]->NumberValue();
        Local<Number> num = Number::New(isolate,value);

        args.GetReturnValue().Set(num);      
    }

    
}